import java.util.concurrent.Semaphore;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 09 - 20
 * Time: 13:22
 */
//实现两个线程增加同一个变量，使用Semphore来控制线程安全.
public class Demo7 {
    static int n = 0;
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(1);
        semaphore.acquire();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                n++;
            }
            semaphore.release();
        });
        t1.start();
        semaphore.acquire();
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                n++;
            }
            semaphore.release();
        });
        t2.start();
        semaphore.acquire();
        System.out.println(n);
    }
}
